package com.ptswitch.material.pages.material;

import org.apache.tapestry5.EventConstants;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.ioc.annotations.Inject;

import com.ptswitch.material.model.material.Material;
import com.ptswitch.material.model.material.MaterialAttachment;
import com.ptswitch.material.pages.base.PageBase;
import com.ptswitch.material.service.MaterialAttachmentService;
import com.ptswitch.material.service.MaterialService;
import com.ptswitch.material.util.HlogConstants;
import com.ptswitch.material.util.WebUtil;
import com.ptswitch.material.util.security.PermissionUtil;

public class DeleteMaterial extends PageBase {
    @Inject
    private MaterialService materialSer;
    @Inject
    private MaterialAttachmentService uploadSer;

    @OnEvent(value = EventConstants.ACTIVATE)
    Object delete(long id) {
        checkPermitted(PermissionUtil.MaterialDelete);
        Material material = materialSer.findById(id, MaterialService.Init_BomMaterials | MaterialService.Init_Uploads);
        if (material == null) {
            return null;
        }
        if (!material.getBomMaterials().isEmpty()) {
            //bom material must empty
            return null;
        }
        for (MaterialAttachment upload : material.getAttachments()) {
            WebUtil.delete(upload);
            uploadSer.delete(upload);
        }
        materialSer.delete(material);
        hlog(HlogConstants.deleteMaterial, material);
        return ListMaterial.class;
    }
}
